﻿using System;
using System.Collections.Generic;
using System.Text;
using System.IO;

namespace Atosenet.Utility
{
    public class TextFileLogWriter : Executor<string>
    {
        #region 成员

        

        #endregion


        #region 初始化

        public TextFileLogWriter(string name, string path)
            : this(name, path, LogFrequency.EveryDay)
        {
            FilePath = path;
        }

        public TextFileLogWriter(string name, string path, LogFrequency logFreq)
            : base(name)
        {
            Name = name;
            FilePath = path;
            LogFileFrequency = logFreq;
        }

        #endregion


        #region 公开函数

        public void Trace(string msg)
        {
            Execute(msg);            
        }

        #endregion


        #region 核心函数
                
        protected override bool ExecutingProcess(string data)
        {
            if (!Directory.Exists(FilePath))
                Directory.CreateDirectory(FilePath);

            string fn = Path.Combine(FilePath, GetLogFilename());

            using (StreamWriter sw = new StreamWriter(fn, true, Encoding.Unicode))
            {
                sw.WriteLine(data);
                sw.Close();
            }
            return true;
        }

        private string GetLogFilename()
        {
            string dateStr = string.Empty;
            DateTime dt = DateTime.Now;

            switch (LogFileFrequency)
            {
                case LogFrequency.EveryMiniute:
                    dateStr = dt.ToString("yyyy-MM-dd HH_mm");
                    break;
                case LogFrequency.EveryHour:
                    dateStr = dt.ToString("yyyy-MM-dd HH_00");
                    break;
                case LogFrequency.EveryDay:
                    dateStr = dt.ToString("yyyy-MM-dd");
                    break;
                case LogFrequency.EveryMonth:
                    dateStr = dt.ToString("yyyy-MM");
                    break;
                default:
                    break;
            }
            return string.Format("{0}_LOG[{1}].log", Name, dateStr);
        }

        #endregion


        #region 属性

        public string FilePath
        {
            get;
            set;
        }

        public LogFrequency LogFileFrequency
        {
            get;
            set;
        }

        #endregion


        #region 附件

        public enum LogFrequency
        {
            EveryMiniute = 0,
            EveryHour = 1,
            EveryDay =2,
            EveryMonth = 3
        }

        #endregion
    }
}
